#include "../Misc/part1_shared.h"


FILE *open_file(char * file_path);
int write_to_file(FILE *file, char *string);

int main(int argc, char** argv)
{
	FILE *users_file;
	BasicHashFunctionPtr hash;
	char *hash_function = argv[1];
	char *file_path = argv[2];
	char username[MAX_INTPUT_SIZE];
	char password[MAX_INTPUT_SIZE];
	char hashed_password[MAX_HASH_SIZE];
	char user_input[MAX_INTPUT_SIZE];
	int valid_input = 0;
	int status = 0;

	if (argc != 3) {
		fprintf(stderr ,"Error: Usage create_authentication <hash function name> <filename to create>\n");
		exit(1);
	}

	if (!strcmp(hash_function, "MD5")) {
		hash = MD5BasicHash;
	} else if (!strcmp(hash_function, "SHA1")) {
		hash = SHA1BasicHash;
	} else {
		fprintf(stderr, "Error: Hash %s is not supported\n", hash_function);
		exit(1);
	}

	/* lets create our file */
	users_file = open_file(file_path);

	/* write the hash function name at the begining of the file */
	status = fprintf(users_file, "%s\n", hash_function);
	if (status < 0) {
		fclose(users_file);
		remove(file_path);
	}
	status = fseek(users_file , 0, SEEK_CUR);
	if (status !=0) {
		fclose(users_file);
		remove(file_path);
	}

	while (1) {
		printf(">>");
		if (read_input(user_input) == -1) continue;
		if (!strcmp(user_input, "quit")) {
			fclose(users_file);
			exit(1);
		}
		/* empty entry */
		if (*user_input == '\0') {
			continue;
		}
		valid_input = extract_username_and_passowrd(user_input, username, password);
		if (valid_input) {
			write_to_file(users_file, username);
			status = fputc('\t', users_file);
			if (status != '\t') {
				fclose(users_file);
				remove(file_path);
			}
			hash_password(hash, password, hashed_password);
			write_to_file(users_file, hashed_password);
			status = fputc('\n', users_file);
			if (status != '\n') {
				fclose(users_file);
				remove(file_path);
			}
		}
		else {
			fprintf(stderr, "Error: Commands are either \"quit\" or <user name>tab<password>\n");
		}
	
	}

	fclose(users_file);
}

FILE *open_file(char * file_path) {
	FILE *file;
	/* first lets check the file doesnt already exist. we wouldnt want to destroy some file */
	file = fopen(file_path, "r");
	if (file) {
		perror(file_path);
		fclose(file);
		exit(1);
	}
	/* now lets create it for writing */
	file = fopen(file_path, "w");
	if (file == NULL) {
		perror(file_path);
		exit(1);
	}
	return file;
}

int write_to_file(FILE *file, char *string) {
	int status = 0;
	status = fprintf(file, "%s", string);
	if (status < 0) {
		fclose(file);
		remove(string);
		exit(1);
	}
	status = fseek(file , 0, SEEK_CUR);
	if (status !=0) {
		fclose(file);
		remove(string);
		exit(1);
	}
	return 1;
}

